﻿using UnityEngine;
using System.Collections;
using UnityEngine.Events;

namespace Lost{
	/// <summary>
	/// 放东西的物品（卡位）
	/// </summary>
	public class PlaceItem : InteractiveItem {
		///需要的物品名
		public string[] ItemsNeeded{
			get{ return itemsNeeded;}
			set{ itemsNeeded = value;}
		}
		[SerializeField] protected string[] itemsNeeded;
		///交互后物品放哪？
		[SerializeField] protected Transform itemPos;
		///进入了触发器且名为ItemName之一的ItemTag
		public ItemTag FitItem{get{return fitItem;}}
		ItemTag fitItem;
		public string PlaceValue{get{return (fitItem != null ? fitItem.ItemName : ""); }}

		[SerializeField] float triggerRadius = 0.2f;

		[SerializeField] public UnityEvent onValueChanged;

		void Awake(){
			//添加触发器和刚体，如果有就不添加了
			SphereCollider newTrigger;
			Rigidbody newRigidbody;
			Collider trigger = GetComponent<Collider> ();
			if (trigger == null || trigger.isTrigger == false) {
				newTrigger = gameObject.AddComponent<SphereCollider> ();
				newTrigger.isTrigger = true;
				newTrigger.radius = triggerRadius;
			}
			Rigidbody rb = GetComponent<Rigidbody> ();
			if (rb == null) {
				newRigidbody = gameObject.AddComponent<Rigidbody> ();
				newRigidbody.useGravity = false;
			}
		}

		void OnTriggerEnter(Collider col){
			if (fitItem != null) {
				return;
			}
			ItemTag it = col.gameObject.GetComponent<ItemTag> ();
			if (it != null) {
				foreach (string s in itemsNeeded) {
					if (it.ItemName == s) {
						Debug.Log (it.ItemName + " Enter");
						fitItem = it;
						SetItemPlace ();
					}
				}
			}
		}
		void OnTriggerExit(Collider col){
			ItemTag it = col.gameObject.GetComponent<ItemTag> ();
			if (it != null) {
				if (it.ItemName == fitItem.ItemName) {
					Debug.Log ("Exit");
					fitItem = null;
				}
			}
		}

		//放置进入范围的物品
		void SetItemPlace()
		{
			GameObject itemHolding = fitItem.gameObject;
			GameObject colon = GameObject.Instantiate (itemHolding, itemPos.position, itemPos.rotation) as GameObject;
			colon.transform.localScale = itemHolding.transform.lossyScale;
			colon.transform.parent = itemPos;
			//colon.name = itemHolding.name;

			ItemsManager.iDestroy (fitItem.gameObject);
			BackpackInteraction.UseItem (fitItem.ItemName);
			fitItem = colon.GetComponent<ItemTag>();

			onValueChanged.Invoke ();
		}

		public void AddListener(UnityAction e){
			if (onValueChanged == null) {
				onValueChanged = new UnityEvent ();
			}
			onValueChanged.AddListener (e);
		}
	}
}
